<?php

namespace app\api\controller;

use app\admin\model\Paper;
use app\api\model\System as SystemModel;
use app\api\model\User as UserModel;
use app\BaseController;
use app\lib\MiniWechat;
use app\lib\tool\Str;
use think\facade\Cache;
use think\Request;

class User extends BaseController
{
    /* 自动加载 */
    public function initialize()
    {
        $this->uid = $this->request->uid;
    }

    /* 检测token合法性 */
    public function checkToken()
    {
        if (!$this->request->auth) {
            return show(config('status.auth'), 'Authorization Failed');
        } else {
            return show(config('status.success'), 'Token合法');
        }
    }

    /* 授权登录[H5] */
    public function login()
    {
        $mini = new MiniWechat;
        $data = $mini->code2Session(input('code', ''));
        if (!is_array($data) || !array_key_exists('session_key', $data) || !array_key_exists('openid', $data) ) {
            return show($data['errcode'], '微信获取信息失败：' . $data['errmsg']);
        }

        $openId = $data['openid'];
//        $openId = 'oSCT25YW5sDE8piiJArc27Q5o1W8';
        $userInfo = \app\admin\model\User::where('openid', $openId)->find();
        if (!empty($userInfo)) {
            $userInfo->wxname = input('post.wxname');
            $userInfo->wximage = input('post.wximage');
            $userInfo->save();
        } else {
            $userInfo = UserModel::create([
                'wxname' => input('post.wxname'),
                'wximage'=> input('post.wximage'),
                'openid' => $openId,
                'phone'  => ''
            ]);
        }
        $userInfo = $userInfo->toArray();
        $userInfo['session_key'] = $data['session_key'];
        $token = Str::getToken();
        Cache::set(config('cache.stores.redis.prefix') . $token, $userInfo, config('cache.stores.redis.timeout'));
        return show(config('status.success'), '登录成功', ['token' => $token]);
    }

    public function getOrders()
    {

    }

    // 设置姓名
    public function updateName()
    {
//        if (! $this->request->auth) {
//            return show(config('status.error'), '请登录');
//        }
        $userId = request()->uid;
        $userId = 1;
        \app\admin\model\User::where('id', $userId)->update(['name' => \request()->post('name')]);
        return show(config('status.success'),  'success');
    }

    // 修改密码
    public function updatePwd()
    {
//        if (! $this->request->auth) {
//            return show(config('status.error'), '请登录');
//        }
        request()->uid = 1;
        $password = $this->request->post('oldpwd');
        $newPassword = $this->request->post('new_password');
        if (empty($password)) {
            return show(-1, '请填写原密码');
        }
        if (strlen($newPassword) < 6) {
            return show(-1, '新密码不得少于六位');
        }

        $user = \app\admin\model\User::find(\request()->uid);
        if ($user->web_passwrod != get_password($password)) {
            return show(-1, '密码不正确');
        }

        $user->web_passwrod = get_password($newPassword);
        $user->save();
        return show(config('status.success'),  'success');
    }

    public function createReocrd(Request $request)
    {
//        if (! $this->request->auth) {
//            return show(config('status.error'), '请登录');
//        }

        Paper::create([
            'user_id' => \request()->uid,
            'type' => $request->post('type'),
            'paper_type' => $request->post('paper_type'),
            'subject_type' => $request->post('subject_type'),
            'year' => $request->post('year'),
            'pics' => $request->post('pics'),
            'title' => $request->post('title'),
            'content' => $request->post('content'),
            'order_num' => buildOrderNum(),
            'is_attr' => $request->post('is_attr', 0),
        ]);

        return show(config('status.success'),  'success');
    }

    // 上传图片
    public function uploadImage()
    {
        // 获取表单上传文件l
        $files = request()->file();
        try {
            validate(['image'=>'filesize:209715'])
                ->check($files);
            $savename = [];
            foreach($files as $file) {
                $savename[] = \think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
            }
            return show(config('status.success'), '操作成功', ['path' => $savename[0]]);
        } catch (\think\exception\ValidateException $e) {
            return show(config('status.error_system'),  $e->getMessage());
        }
    }

    // 绑定手机号
    public function bindPhoneNumber()
    {
       if (!$this->request->auth) {
            return show(config('status.error'), '请登录');
        }
        $userInfo = request()->userInfo;
        $sessionKey    = $userInfo['session_key'];
        $encryptedData = input('post.encryptedData');
        $iv = input('post.iv');
        if (empty($encryptedData) || empty($iv))  {
            return show(config('status.error_system'), '缺少必要参数');
        }

        $mini = new MiniWechat;
        $result = $mini->decode($iv, $sessionKey, $encryptedData);
        if (!is_array($result) || !array_key_exists('phoneNumber', $result)) {
            return show(config('status.error_system'), '手机号获取失败：'. (is_array($result) ? $result['errMsg'] : ''));
        }
        UserModel::where('id', $userInfo['id'])->update(['phone' => $result['phoneNumber']]);
        return show(config('status.success'), '绑定成功', ['phone' => $result['phoneNumber']]);
    }

    public function getUserInfo(Request $request)
    {
//        if (!$this->request->auth) {
//            return show(config('status.error'), '请登录');
//        }
        $this->request->uid = 1;
        $user = \app\api\model\User::field('id,wxname,wximage,name')->where('id', $this->request->uid)->find();
        if (empty($user)) {
            return show(config('status.success'), 'success', []);
        }
        if (empty($user->wxname))  $user->wxname='';
        if (empty($user->wximage)) $user->wximage='';
        return show(config('status.success'), 'success', $user);
    }

    /* 设置 */
    public function setInfo()
    {
        if (!$this->request->auth) return show(config('status.auth'), 'Authorization Failed');
        $field = input('field', '');
        $value = input('value', '');
        UserModel::update([
            'id' => $this->uid,
            $field => $value
        ]);
        return show(config('status.success'), '设置用户信息');
    }
}
